package com.example.mall.common.config;

import com.example.mall.common.constants.BaseEnum;
import com.example.mall.common.constants.EnumDict;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import com.google.common.base.Strings;
import lombok.SneakyThrows;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;

/**
 * @author Mickey
 * @since 2020.08.21
 */
@Configuration
public class ObjectMapperConfig {

    @Bean
    @Primary
    public ObjectMapper objectMapper() {
        return new Jackson2ObjectMapperBuilder()
                //未知属性不会报错
                .failOnUnknownProperties(false)
                //字段单词下划线隔开
//                .propertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE)
                //反序列化
                .deserializerByType(Instant.class, new InstantCustomDeserializer())
                //Long类型 转换String
                .serializerByType(Long.class, ToStringSerializer.instance)
                //Instant类型 转换成字符串时间
                .serializerByType(Instant.class, new InstantCustomSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")))
                //枚举
                .serializerByType(BaseEnum.class, new BaseEnumSerializer())
                //过滤null的字段
                .serializationInclusion(JsonInclude.Include.NON_NULL)
                .build();
    }

    /**
     * instant 序列化
     */
    public static class InstantCustomSerializer extends JsonSerializer<Instant> {

        private final DateTimeFormatter format;

        private InstantCustomSerializer(DateTimeFormatter formatter) {
            this.format = formatter;
        }

        @Override
        public void serialize(Instant instant, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
            if (instant == null) {
                return;
            }
            String jsonValue = format.format(instant.atZone(ZoneId.systemDefault()));
            jsonGenerator.writeString(jsonValue);
        }
    }

    /**
     * instant 反序列化
     */
    public static class InstantCustomDeserializer extends JsonDeserializer<Instant> {

        @SneakyThrows
        @Override
        public Instant deserialize(JsonParser p, DeserializationContext ctxt) {
            String valueAsString = p.getValueAsString();
            if (Strings.isNullOrEmpty(valueAsString)) {
                return null;
            }
            Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(valueAsString);
            return date.toInstant();
        }
    }

    /**
     * 枚举序列化
     */
    public static class BaseEnumSerializer extends JsonSerializer<BaseEnum<?>> {

        @Override
        public void serialize(BaseEnum<?> value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
            gen.writeObject(new EnumDict(value.getName(), value.getCode()));
        }
    }

}
